// src/store/cart.js
import { defineStore } from "pinia";
import { reactive, computed } from "vue";

export const useCartStore = defineStore("cart", () => {
  const cartItems = reactive([]);

  function addProductToCart(product) {
    const existingItem = cartItems.find((item) => item.id == product.id);
    if (existingItem) {
      existingItem.quantity++;
      existingItem.totalPrice = existingItem.price * existingItem.quantity; // 更新商品总价
    } else {
      cartItems.push({ ...product, quantity: 1, totalPrice: product.price });
    }
  }

  function removeProductFromCart(productId) {
    cartItems.splice(
      cartItems.findIndex((item) => item.id == productId),
      1
    );
  }

  function updateCartItemQuantity(productId, newQuantity) {
    const item = cartItems.find((item) => item.id == productId);
    if (item) {
      if (newQuantity == 0) {
        // 如果数量为0，则删除商品
        removeProductFromCart(productId);
      } else {
        // 否则，更新商品数量
        item.quantity = newQuantity;
        item.totalPrice = item.price * item.quantity; // 更新商品总价
      }
    }
  }

 

  const totalItems = computed(() =>
    cartItems.reduce((total, item) => Number(total) + Number(item.quantity), 0)
  );
  const totalPrice = computed(() =>
    cartItems.reduce(
      (total, item) => Number(total) + Number(item.totalPrice),
      0
    )
  );

  return {
    cartItems,
    addProductToCart,
    removeProductFromCart,
    updateCartItemQuantity,
    totalItems,
    totalPrice,
  };
});
